import logging

from sqlalchemy import and_

from api.contexts.rule_enum import  RuleType
from api.service.rule_config_service import rule_manager
from api.service.rule_storage_service import rule_storage
from api.service.rule_transfer_service import transform_rule_to_workflow
from models.engine import db
from models.rule import ReMaterialRule

logger = logging.getLogger(__name__)


def reload_rule(active=None, del_flag=None, rule_code=None):
    # 存放所有需要的过滤条件
    filters = []

    # 只有传了值才加条件
    if active is not None:
        filters.append(ReMaterialRule.active == active)

    if del_flag is not None:
        filters.append(ReMaterialRule.del_flag == del_flag)

    if rule_code is not None and rule_code != '':
        filters.append(ReMaterialRule.rule_code == rule_code)

    # 构建查询
    if filters:
        query = db.session.query(ReMaterialRule).filter(and_(*filters))
    else:
        # 如果没有任何条件，查询全部（谨慎！）
        query = db.session.query(ReMaterialRule)

    for item in query.yield_per(1000):
        try:
            # 直接使用 __dict__，但过滤掉内部属性
            data = {k: v for k, v in item.__dict__.items() if not k.startswith('_')}
            # 提取字段
            rule_code = data['rule_code']
            attr_classify = data['attr_classify']
            attr_type = data['attr_type']
            if (attr_type == RuleType.basics_single.code
                    or attr_type == RuleType.basics_multi.code):
                attr_classify = RuleType.RULE_COMMON_CATE.code
            if data['active'] == False or data['del_flag'] == True:
                try:
                    rule_storage.remove_by_code(rule_code)
                    rule_manager.delete(rule_code)
                except (KeyError, ValueError) as e:
                    pass
            else:
                rule_data = transform_rule_to_workflow(data)
                if rule_storage.exists_code(rule_code):
                    rule_storage.remove_by_code(rule_code)
                rule_storage.add_dict(attr_classify, rule_code, rule_data)
                rule_manager.add(rule_code, data)
        except Exception as e:
            logger.error(e)
    db.session.close()
